<?php
class ContentController extends Controller
{
    public $layout='//layouts/cms_layout';
    public $showTree = true;
	
    public function actionEdit($id)
	{
        $model = new Content;		
	    //$baseUrl = Yii::app()->baseUrl; 
        if(isset($id))
        {
            $model = $model->findByPk($id);
            if($model->parent_id == 0) // Parent node	    
            {
            	$url = $this->createAbsoluteUrl('cms/getContent').'/';
            	// Expand children nodes
            	$childrenNodes = $model->findAllByAttributes(array('parent_id' => $id));
            	
/*				$this->widget('application.extensions.SimpleTreeWidget',array(
					'model'=>'Content',
				    'modelPropertyParentId' => 'parent_id',
				    'modelPropertyId'=>'id',
				    'modelPropertyName' => 'name',
				    'modelPropertyPosition' =>'seq_number',
				
				    'ajaxUrl' => $this->createAbsoluteUrl('cms/simpletree'),
				    'theme' =>'classic',
				    'onSelect'=>'
				        //alert(data.inst.get_selected().text());
				        var id = data.inst.get_selected().attr("id").replace("node_","");
				       $("#content-box").load("'.$url.'"+id);
				    '
				));	*/
            }
            else 
            {
            	// Open content node in edit mode.
		        $cs = Yii::app()->getClientScript();
		        $cs->registerCssFile(Yii::app()->baseUrl.'/css/form.css');
		        $viewVars = $this->_saveContent($id);
		        $this->render('edit', $viewVars);
            }
        }
	}
    
	protected function _saveContent($id = null)
	{
        $model = new Content;
		        
        if(isset($id)){
            $model = $model->findByPk($id);
        }
        if(isset($_POST['Content']))
        {
            $model->attributes=$_POST['Content'];
            if($model->validate() && $model->save())
            {            	
            	$childModelName = $model->contentType->name; 
            	$childModel = new $childModelName;
            	$childModel = $childModel->findByAttributes(array('content_id' => $id));   
            	
            	if(!empty($childModel))
            	{
            		if(isset($_POST[$childModelName]))
            		{
               			$childModel->attributes = $_POST[$childModelName];
	            		$childModel->save();
            		}
            	}
            	else{
            		$childModel = new $childModelName;
            		$childModel->content_id = $model->id;
            		$childModel->save(); 
            	}   
            }
        }
        
        //$findConditions = isset($id) ? "id != $id" : null;
        if(isset($id))
        	$parentList = Content::model()->findAll("id != $id");
        else
        	$parentList = Content::model()->findAll();
        
        $newParentList = array(''=>'root');
        if(!empty($parentList)){
            $parentList = CHtml::listData($parentList, 'id', 'name');
            //$newParentList = array_push($newParentList, $parentList);
            $newParentList = $newParentList+ $parentList;
        }
        
        $contentTypes = CHtml::listData(ContentType::model()->findAll(), 'id', 'name');
        $applications = CHtml::listData(Application::model()->findAll(), 'id', 'name');
        $contentStatuses = CHtml::listData(ContentStatus::model()->findAll(), 'id', 'name');
        $viewVars = array(
            'model'=>$model,
            'parentList'=>$newParentList,
            'contentTypes'=>$contentTypes,
            'applications'=>$applications,
            'contentStatuses'=>$contentStatuses
        );
        return $viewVars;
    }
    
    /*public function actionAdd()
    {
        $viewVars = $this->_saveContent();
        $this->render('add', $viewVars);
    }*/
    
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$viewVars = $this->_saveContent();
        $this->render('create', $viewVars);
	}
    
	public function actionIndex()
	{
		$this->render('index');
	}

	public function actionView()
	{
		$this->render('view');
	}
	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Content::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}